public class MyLeetCode {
    //删除元素
    class ListNode{
        int val;
        ListNode next;
        public ListNode(int val) {
            this.val = val;
        }
        public ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }

        //链表中删除所有值为val的元素
        public  ListNode removeElements(ListNode head, int val) {
            //链表为空的情况下
            if(head == null){
                return head;
            }
            //头结点的值等于val并且链表中元素所有值都为val的情况下
            while(head!=null &&head.val == val){
                head = head.next;
            }
            ListNode cur = head;
            ListNode prevnode = cur;
            while(cur!= null){
            /*if(cur == head && cur.val == val){
                head = head.next;
                cur = head;
                prevnode = cur;
            }else*/if(cur.val == val){
                    prevnode.next = cur.next;
                    cur = cur.next;
                }else{
                    prevnode = cur;
                    cur = cur.next;
                }
            }
            return head;
        }
    }
}
